﻿using Common.Extension;

namespace DesignModeConsole.行为型.解释器模式.告警规则进阶;

/// <summary>
/// 告警表达式
/// </summary>
public interface IAlertRuleExpression2
{
    bool Interpret(Dictionary<string, long> statusDic);
}

/// <summary>
/// 大于表达式
/// </summary>
public class DaYuExpression2 : IAlertRuleExpression2
{
    private readonly string _key;
    private readonly long _value;

    public DaYuExpression2(string key, long value)
    {
        _key = key;
        _value = value;
    }

    public DaYuExpression2(string expression)
    {
        var elements = expression.Trim().Split(" ");
        if (elements.Length != 3 || !elements[1].Trim().Equals(">"))
        {
            throw new ArgumentException("无效的表达式");
        }

        _key = elements[0].Trim();
        _value = elements[2].Trim().ToInt64();
    }

    public bool Interpret(Dictionary<string, long> statusDic)
    {
        if (!statusDic.TryGetValue(_key, out var value))
            return false;

        return value > _value;
    }
}

/// <summary>
/// 小于
/// </summary>
public class XiaoYuExpression2 : IAlertRuleExpression2
{
    private readonly string _key;
    private readonly long _value;

    public XiaoYuExpression2(string key, long value)
    {
        _key = key;
        _value = value;
    }

    public XiaoYuExpression2(string expression)
    {
        var elements = expression.Trim().Split(" ");
        if (elements.Length != 3 || !elements[1].Trim().Equals("<"))
        {
            throw new ArgumentException("无效的表达式");
        }

        _key = elements[0].Trim();
        _value = elements[2].Trim().ToInt64();
    }

    public bool Interpret(Dictionary<string, long> statusDic)
    {
        if (!statusDic.TryGetValue(_key, out var value))
            return false;

        return value < _value;
    }
}

/// <summary>
/// 等于表达式
/// </summary>
public class EqualExpression2 : IAlertRuleExpression2
{
    private readonly string _key;
    private readonly long _value;

    public EqualExpression2(string key, long value)
    {
        _key = key;
        _value = value;
    }

    public EqualExpression2(string expression)
    {
        var elements = expression.Trim().Split(" ");
        if (elements.Length != 3 || !elements[1].Trim().Equals("="))
        {
            throw new ArgumentException("无效的表达式");
        }

        _key = elements[0].Trim();
        _value = elements[2].Trim().ToInt64();
    }

    public bool Interpret(Dictionary<string, long> statusDic)
    {
        if (!statusDic.TryGetValue(_key, out var value))
            return false;

        return value == _value;
    }
}